# -*- coding: utf-8 -*-

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

import json

import mainui
import xlsx


class MainWindow(QMainWindow):
    workbook = 0
    worksheet = 0

    sheetdatawithname = {}
    sheetdata = 0
    colcount = 0
    rowcount = 0
    comboClasses = []
    comboMatchRules = []
    lineEditMatchTargets = []

    memberbook = 0
    members = []
    memberWorks = {}

    procurementbook = 0
    procurementsheet = 0

    cfgfile = "ljdz.cfg"
    cfg = {}

    rowsdict = {}

    def __init__(self):
        # 信号量
        super(MainWindow, self).__init__()
        self.ui = mainui.Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle("阿米巴经营会计算账软件")
        self.loadcfg()
        self.setupmyUI()

    def loadcfg(self):
        try:
            fd = open(self.cfgfile, "r")
            self.cfg = json.load(fd)
            fd.close()
        except (FileNotFoundError, json.decoder.JSONDecodeError):
            self.cfg["分组栏目"] = "二级吧"
            self.cfg["数据条目行"] = 2
            self.cfg["项目号行"] = 2
            self.cfg["项目号名字"] = "项目号"
            self.cfg["产品方向名字"] = "产品方向"
            self.cfg["采购条目行"] = 2
            fd = open(self.cfgfile, "w")
            json.dump(self.cfg, fd)
            fd.close()

    def savecfg(self):
        fd = open(self.cfgfile, "w")
        json.dump(self.cfg, fd)
        fd.close()

    def changecfg(self):
        self.cfg["分组栏目"] = self.ui.lineEditMatchSheetString.text()
        self.cfg["数据条目行"] = int(self.ui.lineEditDataSheetRowNumber.text())
        self.cfg["项目号行"] = int(self.ui.lineEditMemberSheetRowNumber.text())
        self.cfg["项目号名字"] = self.ui.lineEditMatchSheetString.text()
        self.cfg["产品方向名字"] = self.ui.lineEditMemberSheetString.text()
        self.cfg["采购条目行"] = int(self.ui.lineEditProcurementSheetRowNumber.text())
        self.savecfg()

    def setupmyUI(self):

        self.comboClasses.append(self.ui.comboClass0)
        self.comboClasses.append(self.ui.comboClass1)
        self.comboClasses.append(self.ui.comboClass2)
        self.comboClasses.append(self.ui.comboClass3)

        self.comboMatchRules.append(self.ui.comboMatchRule0)
        self.comboMatchRules.append(self.ui.comboMatchRule1)
        self.comboMatchRules.append(self.ui.comboMatchRule2)
        self.comboMatchRules.append(self.ui.comboMatchRule3)

        self.lineEditMatchTargets.append(self.ui.lineEditMatchTarget0)
        self.lineEditMatchTargets.append(self.ui.lineEditMatchTarget1)
        self.lineEditMatchTargets.append(self.ui.lineEditMatchTarget2)
        self.lineEditMatchTargets.append(self.ui.lineEditMatchTarget3)

        self.ui.lineEditDataFile.setEnabled(False)
        self.ui.lineEditMemberFile.setEnabled(False)

        self.ui.lineEditDataSheetRowNumber.setText(str(self.cfg["数据条目行"]))
        self.ui.lineEditDataSheetRowNumberMatch.setEnabled(False)
        self.ui.lineEditDataSheetRowNumberMatch.setText(str(self.cfg["数据条目行"]))
        self.ui.lineEditProcurementSheetRowNumber.setText(str(self.cfg["采购条目行"]))
        self.ui.lineEditMemberSheetRowNumber.setText(str(self.cfg["项目号行"]))

        self.ui.lineEditWorkSheetString.setText(str(self.cfg["项目号名字"]))
        self.ui.lineEditMemberSheetString.setText(str(self.cfg["产品方向名字"]))
        self.ui.lineEditMatchSheetString.setText(str(self.cfg["分组栏目"]))

        self.ui.lineEditDataSheetRowNumber.textChanged.connect(self.changecfg)
        self.ui.lineEditMemberSheetRowNumber.textChanged.connect(
            self.changecfg)
        self.ui.lineEditWorkSheetString.textChanged.connect(self.changecfg)
        self.ui.lineEditMemberSheetString.textChanged.connect(self.changecfg)
        self.ui.lineEditMatchSheetString.textChanged.connect(self.changecfg)

        # 绑定选择数据文件的按钮
        self.ui.buttonSelectDataFile.clicked.connect(self.selectDataFile)
        # 绑定分解数据文件的按钮
        self.ui.buttonDecomData.clicked.connect(self.decomData)
        # 绑定选择采购文件的按钮
        self.ui.buttonSelectProcurementFile.clicked.connect(self.selectProcurementFile)
        # 绑定分析采购文件的按钮
        self.ui.buttonDecomProcurement.clicked.connect(self.decomProcurement)

        # 绑定选择分组文件的按钮
        self.ui.buttonSelectMemberFile.clicked.connect(self.selectMemberFile)
        # 绑定分解分组文件的按钮
        self.ui.buttonDecomMember.clicked.connect(self.decomMember)
        # 绑定一键分组数据的按钮
        self.ui.buttonSortByMember.clicked.connect(self.sortByMember)
        # 绑定查找数据的按钮
        self.ui.buttonFindData.clicked.connect(self.finddata)


        # 项目费用柱状图
        self.ui.buttonWorkCost.clicked.connect(self.drawWorkCostPic)

    def syslog(self, info):
        self.ui.textEditLogInfo.append(str(info))

    def selectDataFile(self):
        filepath = QFileDialog.getOpenFileName(self, str('数据文件'), None, \
                                               "xlsx(*.xlsx);;xlsm(*.xlsm);;xltx(*.xltx);;xltm(*.xltm);;所有文件(*)")
        filepath = filepath[0]
        if filepath == '':
            return
        self.ui.lineEditDataFile.setText(filepath)
        self.workbook = xlsx.setxlsxboot(filepath)
        if self.workbook == None:
            self.syslog("选择的文件格式不正确，仅支持.xlsx,.xlsm,.xltx,.xltm")
        sheetnames = xlsx.getsheet(self.workbook)

        ncount = self.ui.comboDataSheet.count()
        for _ in range(0, ncount):
            self.ui.comboDataSheet.removeItem(0)
        for name in sheetnames:
            self.ui.comboDataSheet.addItem(name)

    def decomData(self):
        self.sheetdatawithname = {}
        self.worksheet = []
        filepath = self.ui.lineEditDataFile.text()
        sheetname = self.ui.comboDataSheet.currentText()
        self.worksheet = xlsx.getsheetdata(self.workbook, sheetname)
        self.colcount = self.worksheet.max_column
        try:
            rownumber = int(self.ui.lineEditDataSheetRowNumber.text())
        except:
            self.syslog("无效的标题行号(1)，采用默认配置2")
            rownumber = 2
        for combo in self.comboClasses:
            assert isinstance(combo, QComboBox)
            ncount = combo.count()
            for _ in range(0, ncount):
                combo.removeItem(0)
            for n in range(0, self.colcount):
                combo.addItem(
                    self.worksheet.cell(column=n + 1, row=rownumber + 1).value)

        ncount = self.ui.comboClassForSort.count()
        for _ in range(0, ncount):
            self.ui.comboClassForSort.removeItem(0)
        n = 0
        for col in self.worksheet.columns:

            # 给combo设置值
            self.ui.comboClassForSort.addItem(
                self.worksheet.cell(column=n + 1, row=rownumber + 1).value)
            # 这里是获取col的数据，col出来还是一个生成器
            self.sheetdatawithname[self.worksheet.cell(column=n + 1,
                                                       row=rownumber +
                                                       1).value] = col
            # 查看当前设置的条目是不是默认需要插入数据的栏目
            if self.worksheet.cell(column=n + 1, row=rownumber +
                                   1).value == self.cfg["分组栏目"]:
                self.ui.comboClassForSort.setCurrentIndex(n)
            n += 1


    def selectProcurementFile(self):
        filepath = QFileDialog.getOpenFileName(self, str('采购文件'), None, \
                                               "xlsx(*.xlsx);;xlsm(*.xlsm);;xltx(*.xltx);;xltm(*.xltm);;所有文件(*)")
        filepath = filepath[0]
        if filepath == '':
            return
        # 获取到文件的路径
        self.ui.lineEditMemberFile.setText(filepath)
        # 打开xlsx文件
        self.procurementbook = xlsx.setxlsxboot(filepath)
        if self.procurementbook == None:
            self.syslog("选择的文件格式不正确，仅支持.xlsx,.xlsm,.xltx,.xltm")
            return
        sheetnames = xlsx.getsheet(self.procurementbook)

        ncount = self.ui.comboProcurementSheet.count()
        for _ in range(0, ncount):
            self.ui.comboProcurementSheet.removeItem(0)

        for name in sheetnames:
            self.ui.comboProcurementSheet.addItem(name)


    def decomProcurement(self):
        sheetname = self.ui.comboProcurementSheet.currentText()
        self.procurementsheet = xlsx.getsheetdata(self.procurementbook, sheetname)
        rowcount = self.procurementsheet.max_row
        colcount = self.procurementsheet.max_column
        rowtitle = int(self.ui.lineEditProcurementSheetRowNumber.text())
        for n in range(0, colcount):
            if self.procurementsheet.cell(row=rowtitle, column=n).value == "项目号":
                





    def selectMemberFile(self):
        filepath = QFileDialog.getOpenFileName(self, str('分组文件'), None, \
                                               "xlsx(*.xlsx);;xlsm(*.xlsm);;xltx(*.xltx);;xltm(*.xltm);;所有文件(*)")
        filepath = filepath[0]
        if filepath == '':
            return
        # 获取到文件的路径
        self.ui.lineEditMemberFile.setText(filepath)
        # 打开xlsx文件
        self.memberbook = xlsx.setxlsxboot(filepath)
        if self.memberbook == None:
            self.syslog("选择的文件格式不正确，仅支持.xlsx,.xlsm,.xltx,.xltm")
            return
        sheetnames = xlsx.getsheet(self.memberbook)

        ncount = self.ui.comboMemberSheet.count()
        for _ in range(0, ncount):
            self.ui.comboMemberSheet.removeItem(0)

        for name in sheetnames:
            self.ui.comboMemberSheet.addItem(name)

    def decomMember(self):
        filepath = self.ui.lineEditMemberFile.text()
        self.memberWorks = {}
        for m in self.members:
            works = xlsx.getsheetdata(self.memberbook, m)
            self.memberWorks[m] = []
            for col in works.columns:
                if col[0].value == "项目号":
                    for v in col[1:]:  # 排除项目号的干扰
                        self.memberWorks[m].append(v.value)

    def sortByMember(self):
        filepath = self.ui.lineEditDataFile.text()
        index = self.ui.comboDataSheet.currentIndex()
        colindex = self.ui.comboClassForSort.currentIndex()

        rownum = 0
        for work in self.sheetdatawithname["项目号"]:
            for mem in self.members:
                if work.value in self.memberWorks[mem]:
                    # 给这一行数据标记上分组信息
                    # print("写入数据" + mem + "  " + str(rownum + 1) + "  " +
                    #   str(colindex + 1))
                    xlsx.writesheetdata(self.worksheet, rownum + 1,
                                        colindex + 1, mem)
                    break
            rownum += 1
        xlsx.savesheetwb(filepath, self.workbook)
        self.syslog("分组完毕，请查看数据文件")

    def finddata(self):
        rows = range(0, self.worksheet.max_row)
        ncount = 0

        for lineedit in self.lineEditMatchTargets:
            assert isinstance(lineedit, QLineEdit)
            if lineedit.text() == None or lineedit.text() == "":
                ncount += 1
                continue
            conds = lineedit.text()
            newrows = []
            # 进入条件筛选部分
            self.comboClasses[ncount].currentIndex()
            sheetname = self.comboClasses[ncount].currentText()
            if self.ui.comboRule.currentText() == "与模式":
                if self.comboMatchRules[ncount].currentText() == "精准匹配":
                    self.rowsdict = {}
                    for r in rows:
                        if conds == self.sheetdatawithname[sheetname][r].value:
                            newrows.append(r)
                            try:
                                self.rowsdict[str(r)].append(conds)
                            except KeyError:
                                self.rowsdict[str(r)] = [conds]
                else:
                    self.rowsdict = {}
                    for r in rows:
                        if self.sheetdatawithname[sheetname][r].value is None:
                            continue
                        if conds in self.sheetdatawithname[sheetname][r].value:
                            newrows.append(r)
                            try:
                                self.rowsdict[str(r)].append(conds)
                            except KeyError:
                                self.rowsdict[str(r)] = [conds]
                rows = newrows
            else:
                if self.comboMatchRules[ncount].currentText() == "精准匹配":
                    for r in rows:
                        if conds == self.sheetdatawithname[sheetname][r].value:
                            try:
                                self.rowsdict[str(r)].append(conds)
                            except KeyError:
                                self.rowsdict[str(r)] = [conds]

                else:
                    for r in rows:
                        if self.sheetdatawithname[sheetname][r].value is None:
                            continue
                        if conds in self.sheetdatawithname[sheetname][r].value:
                            try:
                                self.rowsdict[str(r)].append(conds)
                            except KeyError:
                                self.rowsdict[str(r)] = [conds]
            ncount += 1
        print(self.rowsdict)


    def drawWorkCostPic(self):
        workdict = {}
        for key, value in self.rowsdict.items():
            rownum = int(key)
            try:
                workdict[self.sheetdatawithname["项目号"][rownum].value][0] += \
                    self.sheetdatawithname["交易金额\n（不含税）"][rownum].value
                workdict[self.sheetdatawithname["项目号"][rownum].value][1] += \
                    self.sheetdatawithname["应收服务费金额"][rownum].value
                workdict[self.sheetdatawithname["项目号"][rownum].value][2] += \
                    self.sheetdatawithname["结算总额"][rownum].value
            except KeyError:
                workdict[self.sheetdatawithname["项目号"][rownum].value] = []
                workdict[self.sheetdatawithname["项目号"][rownum].value].append(
                    self.sheetdatawithname["交易金额\n（不含税）"][rownum].value)
                workdict[self.sheetdatawithname["项目号"][rownum].value].append(
                    self.sheetdatawithname["应收服务费金额"][rownum].value)
                workdict[self.sheetdatawithname["项目号"][rownum].value].append(
                    self.sheetdatawithname["结算总额"][rownum].value)
        print(workdict)
            